package com.aps.util;

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.io.Resource;

import java.io.*;
import java.util.Properties;

/**
 * Created by Liaoguangan on 2017/8/24 0024.
 */
public class ResourcesUtil {

    private static InputStreamReader getReader(String fileName) {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
        Resource resource = provider.getResourceLoader().getResource(fileName);
        InputStreamReader read = null;
        try {
            read = new InputStreamReader(resource.getInputStream(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return read;
    }

    private static StringBuffer getFileContent(String fileName, Boolean br) {
        try {
            StringBuffer sb = new StringBuffer();
            InputStreamReader read = getReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(read);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                if (br) {
                    sb.append(line + "<br/>");
                } else {
                    sb.append(line);
                }
            }

            bufferedReader.close();
            read.close();
            return sb;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static StringBuffer getCommanFromFileName(String fileName) {
        return getFileContent(fileName, true);
    }

    public static StringBuffer getJson(String fileName) {
        return getFileContent(fileName, false);
    }

    public static String getValueFromProps(String fileName, String key) {
        try {
            Properties props = new Properties();
            InputStreamReader read = getReader(fileName);
            props.load(read);
            return props.get(key).toString();
        } catch (Exception e) {
            return null;
        }
    }

}
